<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" row-key="id" border ref="dataGridRef">
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input v-model="queryData.objectName" placeholder="模型名称/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.modifierType" placeholder="模型性质" clearable>
                                    <el-option
                                        v-for="(value, key) in modifierType"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.activeState" placeholder="状态" clearable>
                                    <el-option
                                        v-for="(value, key) in activeState"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation>
                    <el-button type="primary" @click="operCollect('创建')">新建</el-button>
                </template>
                <el-table-column label="模型名称" width="300" show-overflow-tooltip fixed>
                    <template #default="scope">
                        <el-button link type="primary" @click="operCollect('详情', scope.row)">
                            {{ scope.row.displayName
                            }}{{
                                scope.row.children && scope.row.children.length
                                    ? `（${scope.row.children.length}）`
                                    : ''
                            }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="objectName" label="标识符" show-overflow-tooltip />
                <el-table-column prop="showOrder" label="显示顺序" />
                <el-table-column prop="modifierType" label="模型性质">
                    <template #default="scope">
                        {{ modifierType[scope.row.modifierType] }}
                    </template>
                </el-table-column>
                <el-table-column prop="objectType" label="模型类型">
                    <template #default="scope">
                        {{ objectType[scope.row.objectType] }}
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template #default="scope">
                        <span class="table-item-status" :status="activeState[scope.row.activeState]">
                            {{ activeState[scope.row.activeState] }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="135" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="operCollect('修改', scope.row)">修改</el-button>
                        <el-button
                            link
                            type="danger"
                            @click="operCollect('删除', scope.row)"
                            v-if="
                                scope.row.objectType !== 'SYSTEM' &&
                                scope.row.activeState === 'NEW' &&
                                (!scope.row.children || scope.row.children.length === 0)
                            "
                        >
                            删除
                        </el-button>
                        <el-button
                            link
                            type="primary"
                            @click="operCollect('激活', scope.row)"
                            v-if="scope.row.activeState === 'NEW' && scope.row.modifierType !== 'EXTENDED'"
                        >
                            激活
                        </el-button>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import type { SysMetadataObjectVo } from '@great/services';
import { modelThingService } from '@great/services';
import { showPopupBox } from '@great/utils';
import { useRouter } from 'vue-router';
import { activeState, modifierType, objectType, REQUEST_CODE_MESSAGE, usageType } from '@/utils/constant';
import CreateEditModal from './components/list/CreateEditModal.vue';
import { Block, DataGrid, type DataGridInstance } from '@great/components';
import { checkPermi } from '@/utils/ruoyi';

const router = useRouter();

// 查询条件
const queryData = ref({
    objectName: '',
    modifierType: '',
    activeState: ''
});
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await modelThingService.getPageTree({
            current,
            size,
            usageType: 'BUSINESS',
            ...queryData.value
        });
        return { data: res.data.records, total: res.data.total };
    }
});

/**
 * 操作收集
 * @param type 操作类型
 * @param row 操作行数据
 */
const operCollect = (type: string, row?: SysMetadataObjectVo) => {
    switch (type) {
        case '创建':
            showPopupBox(CreateEditModal, {
                getList: dataGridRef.value?.reset as () => Promise<void>
            });
            break;
        case '详情':
            if (checkPermi(['model:business:detail'])) {
                router.push({
                    name: 'model-business-detail',
                    params: {
                        id: row?.id
                    }
                });
            }
            break;
        case '修改':
            showPopupBox(CreateEditModal, {
                row,
                getList: dataGridRef.value?.refresh as () => Promise<void>
            });
            break;
        case '删除':
            ElMessageBox.confirm(`是否确认删除模型 ${row?.displayName} ？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    await modelThingService.delModel(row?.id as number);
                    ElNotification({
                        title: '删除成功！',
                        type: 'success'
                    });
                    dataGridRef.value?.refresh();
                })
                .catch(() => {});
            break;
        case '激活':
            ElMessageBox.confirm(`是否确认激活模型 ${row?.displayName} ？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(async () => {
                    await modelThingService.extendedObject({
                        objectNames: [row?.objectName as string],
                        extendedObject: true,
                        createType: 1
                    });
                    ElNotification({
                        title: '激活成功！',
                        type: 'success'
                    });
                    dataGridRef.value?.refresh();
                })
                .catch(() => {});
            break;
    }
};
</script>
<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
            }
        }
        .table-item-status[status='未激活'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='激活'] {
            &::before {
                background-color: #67c23a;
            }
        }
    }
}
</style>
